package question_answer

import (
	"encoding/json"
	"news_for_deepseek_interface/controller"
	"news_for_deepseek_interface/logger"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/project/rabbitmq"

	"crypto/rand"
	"encoding/hex"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
)

func Import(c *gin.Context) {
	//form上传文件
	file, err := c.FormFile("file")
	if err != nil {
		controller.Fail(c, controller.ParamsError, err.Error())
		return
	}

	// 获取当前时间
	now := time.Now()

	// 构建年月日目录结构
	dateDir := filepath.Join(
		"uploads",
		now.Format("2006"), // 年
		now.Format("01"),   // 月
		now.Format("02"),   // 日
	)

	// 确保目录存在
	if err := os.MkdirAll(dateDir, 0755); err != nil {
		logger.Error("创建上传目录失败：" + err.Error())
		controller.Fail(c, controller.BusinessError, "创建上传目录失败："+err.Error())
		return
	}

	// 生成随机字符串
	randomBytes := make([]byte, 16)
	if _, err := rand.Read(randomBytes); err != nil {
		logger.Error("生成随机文件名失败：" + err.Error())
		controller.Fail(c, controller.BusinessError, "生成随机文件名失败："+err.Error())
		return
	}
	randomStr := hex.EncodeToString(randomBytes)

	// 获取文件扩展名
	ext := filepath.Ext(file.Filename)

	// 生成新的文件名：时间戳-随机字符串.扩展名
	newFilename := now.Format("150405") + "-" + randomStr + ext // 只用时分秒，因为年月日在目录中

	// 完整的文件路径
	fullPath := filepath.Join(dateDir, newFilename)

	// 保存文件
	if err := c.SaveUploadedFile(file, fullPath); err != nil {
		logger.Error("保存文件失败：" + err.Error())
		controller.Fail(c, controller.BusinessError, "保存文件失败："+err.Error())
		return
	}

	db := model.GetInstance().DB
	var files model.FilesModel
	files.FilePath = fullPath
	files.FileName = newFilename
	files.Status = 0 //  0 待执行 1 执行中 2 执行完成
	files.CreatedAt = time.Now()
	files.UpdatedAt = time.Now()
	if err := db.Create(&files).Error; err != nil {
		logger.Error("保存文件失败1：" + err.Error())
		controller.Fail(c, controller.BusinessError, "保存文件失败1："+err.Error())
		return
	}

	// 构建 MQ 消息
	message := rabbitmq.QuestionAnswerMessage{
		FilePath: fullPath,
		FileId:   files.Id,
	}

	// 序列化消息
	messageBytes, err := json.Marshal(message)
	if err != nil {
		logger.Error("序列化消息失败：" + err.Error())
		controller.Fail(c, controller.BusinessError, "序列化消息失败："+err.Error())
		return
	}

	// 发送消息到 RabbitMQ
	if err := rabbitmq.Publish(
		rabbitmq.QuestionAnswerConfig.ExchangeName,
		rabbitmq.QuestionAnswerConfig.RoutingKey,
		messageBytes,
	); err != nil {
		logger.Error("发送MQ消息失败：" + err.Error())
		controller.Fail(c, controller.BusinessError, "发送MQ消息失败："+err.Error())
		return
	}

	controller.Success(c, "")
}
